﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Aij1.Cms;
using Aij1.Model;
using Aij1.BLL;

namespace Aij1
{
    public partial class SendOrder : BasePage
    {
        protected string Tips;
        B_Order order;
        protected void Page_Load(object sender, EventArgs e)
        {
            PageName = "提交订单";
            Keywords = "亲子照,儿童照,全家福,套系预订,爱+1";
            Description = Config.Description;
            if (CurrentCustomer == null)
            {
                Tips = "您还没有在本站登录，请您点下方“用QQ账号登录”按钮，或点击右上角“用QQ账号登录”的图标，登录后将自动返回本窗口。继续提交您的订单。谢谢！";
            }
            else if (!IsPostBack)
            {
                Tips = String.Format(@" <img src='{0}' />
    <b>{1}</b>{2}: 
感谢您选择了本店的服务，请您核对无误后，点击“提交订单”按钮，我们将在第一时间与您取得联系！", CurrentCustomer.FigureUrl,
 CurrentCustomer.SysName, CurrentCustomer.Gender == 1 ? "先生" : (CurrentCustomer.Gender == 2 ? "女士" : ""));
            }
            else
            {
                P1.Visible = false;
                try
                {
                    ProcessOrder();
                    Tips = String.Format(@" <img src='{0}' />
    <b>{1}</b>{2}: <br />
恭喜! 您的订单已经提交，订单号是: 【{3}】。 本店将在一个工作日内受理。您可以继承浏览本站其他的精彩内容。", CurrentCustomer.FigureUrl,
     CurrentCustomer.SysName, CurrentCustomer.Gender == 1 ? "先生" : (CurrentCustomer.Gender == 2 ? "女士" : ""), order.OrderNo);
                    PageName = "订单提交成功";
                }
                catch (Exception ex)
                {
                    Tips = "报歉！发生了错误，请稍后再试。<br />" + ex.Message;
                }
            }
        }

        private void ProcessOrder()
        {
            List<TempItems> tempShoppingItems = Session["ShoppingCart"] as List<TempItems>;
            if (tempShoppingItems == null || tempShoppingItems.Count == 0)
            {
                Response.Write("没有订单。");
                Response.End();
                return;
            }

            order = new B_Order(XpoSession)
           {
               CustomerId = CurrentCustomer,
               OrderTime = DateTime.Now,
               OrderNo = Config.GetUniqueOrderNo(),
           };

            foreach (var item in tempShoppingItems)
            {
                B_OrderItem oItem = new B_OrderItem(XpoSession)
                {
                    OrderId = order,
                    Count = item.Count,
                    Price = item.Price,
                    SeriesId = XpoSession.GetObjectByKey<B_Series>(item.Oid),
                };
            }

            order.Payable = order.Items.Sum(item => item.Price * item.Count);

            order.Save();

            Session.Remove("ShoppingCart");
        }
    }
}